#!/usr/bin/env node
import fs from 'fs-extra';
import path from 'path';
import { execSync } from 'child_process';
import { rollup } from 'rollup';
import { componentsConfig, utilsConfig } from '../rollup.config.js';

// 获取packages目录
const packagesDir = path.resolve(process.cwd(), 'packages');

// 创建dist目录函数
async function ensureDistDir(packagePath) {
  const distDir = path.join(packagePath, 'dist');
  await fs.ensureDir(distDir);
  console.log(`Created dist directory: ${distDir}`);
}

// 构建单个包
async function buildPackage(config, packageName) {
  console.log(`Building ${packageName}...`);
  try {
    const bundle = await rollup(config);
    await Promise.all(config.output.map(output => bundle.write(output)));
    await bundle.close();
    console.log(`Successfully built ${packageName}`);
  } catch (error) {
    console.error(`Failed to build ${packageName}:`, error);
    throw error;
  }
}

// 生成TypeScript类型定义文件
function generateTypeDefinitions(packagePath) {
  console.log(`Generating type definitions for ${path.basename(packagePath)}...`);
  const packageName = path.basename(packagePath);
  const typesDir = path.join(packagePath, 'dist/types');
  
  // 确保types目录存在
  fs.ensureDirSync(typesDir);
  
  try {
    // 创建临时tsconfig文件
    const tempTsConfig = path.join(packagePath, 'tsconfig.temp.json');
    const tempConfig = {
      extends: '../../tsconfig.json',
      include: ['./src/**/*'],
      exclude: ['node_modules', 'dist'],
      compilerOptions: {
        outDir: './dist/types',
        rootDir: './src',
        declaration: true,
        emitDeclarationOnly: true,
        skipLibCheck: true,
        lib: ['esnext', 'dom']
      }
    };
    
    fs.writeJSONSync(tempTsConfig, tempConfig, { spaces: 2 });
    
    // 使用临时tsconfig文件生成类型定义
    execSync(`npx tsc --project ${tempTsConfig}`, { stdio: 'inherit' });
    
    // 删除临时文件
    fs.unlinkSync(tempTsConfig);
    
    console.log(`Successfully generated type definitions for ${packageName}`);
  } catch (error) {
    console.error(`Failed to generate type definitions for ${packageName}`);
    throw error;
  }
}

// 更新package.json中的导出配置
async function updatePackageJson(packagePath) {
  const packageJsonPath = path.join(packagePath, 'package.json');
  const packageJson = await fs.readJson(packageJsonPath);
  
  packageJson.main = 'dist/index.js';
  packageJson.module = 'dist/index.esm.js';
  packageJson.types = 'dist/types/index.d.ts';
  
  await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 });
  console.log(`Updated package.json for ${path.basename(packagePath)}`);
}

// 主构建函数
async function main() {
  console.log('Starting build process...');
  
  try {
    // 构建components包
    await ensureDistDir(path.join(packagesDir, 'components'));
    await buildPackage(componentsConfig, '@PersonalComprehensiveWeb/components');
    generateTypeDefinitions(path.join(packagesDir, 'components'));
    await updatePackageJson(path.join(packagesDir, 'components'));
    
    // 构建utils包
    await ensureDistDir(path.join(packagesDir, 'utils'));
    await buildPackage(utilsConfig, '@PersonalComprehensiveWeb/utils');
    generateTypeDefinitions(path.join(packagesDir, 'utils'));
    await updatePackageJson(path.join(packagesDir, 'utils'));
    
    console.log('\n🎉 All packages built successfully!');
  } catch (error) {
    console.error('\n❌ Build failed:', error);
    process.exit(1);
  }
}

// 执行构建
main();